package com.jagochan.module.rbac.sys_user.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jagochan.common.result.ResultUtils;
import com.jagochan.module.rbac.common.Constants;
import com.jagochan.module.rbac.common.exception.BusinessException;
import com.jagochan.module.rbac.sys_user.domain.SysUser;
import com.jagochan.module.rbac.sys_user.mapper.SysUserMapper;
import com.jagochan.module.rbac.sys_user.service.SysUserService;
import com.jagochan.module.rbac.sys_user_role.service.SysUserRoleService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;

@Service
@RequiredArgsConstructor
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    private final SysUserRoleService sysUserRoleService;

    @Override
    public void saveUserWithRole(SysUser sysUser) {
        Date now = new Date();
        sysUser.setCreateTime(now);
        sysUser.setUpdateTime(now);
        sysUser.setUserId(null);
        // 新增用户
        int affectNum = getBaseMapper().insert(sysUser);
        if (affectNum < 1) return;
        // 新增角色（为该用户添加角色）
        sysUserRoleService.save(sysUser.getUserId(), sysUser.getRoleId());
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateUserWithRole(SysUser sysUser) {
        sysUser.setUpdateTime(new Date());
        // 编辑用户
        updateById(sysUser);

        // 删除当前用户的所有角色
        sysUserRoleService.removeByUserId(sysUser.getUserId());
        // 为当前用户添加角色
        sysUserRoleService.save(sysUser.getUserId(), sysUser.getRoleId());
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void removeUserWithRole(Long userId) {
        SysUser user = getById(userId);
        if (Objects.equals(user.getIsAdmin(), Constants.IS_ADMIN)) {
            BusinessException.raise("超级管理员不能删除哦");
        }

        // 删除用户
        removeById(userId);
        // 删除用户的角色
        sysUserRoleService.removeByUserId(userId);
    }

    @Override
    public boolean resetPassword(Long userId, PasswordEncoder passwordEncoder) {
        SysUser user = getById(userId);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
        user.setPassword(passwordEncoder.encode(sdf.format(new Date()) + userId + "888"));
        return updateById(user);
    }
}